import React, { Component } from "react";
import { Layout, Form, Button, Divider, notification } from "antd";
import "@/style/view-style/login.less";
import { connect } from "react-redux";
import TheImage from "@/components/TheImage";
import { LoadingOutlined } from "@ant-design/icons";
import ParticlesBg from "particles-bg";
import { passwordReg } from "@/utils/regexp";
import { apiPage } from "../../request/system/menu";
import aesUtil from "../../utils/aes";
import rsaUtil from "../../utils/rsa";
import { encrypt, decode, getCaptcha } from "@/request/auth";
import _ from "lodash";
import { Base64 } from "js-base64";
import JSEncrypt from "jsencrypt";

const mapDispatchToProps = (dispatch) => {
  return {
    updateUser: (data) => {
      dispatch({ type: "set", data });
    },
    updateMenu: (data) => {
      dispatch({ type: "setMenus", data });
    },
    updateIdent: (data) => {
      dispatch({ type: "setIdent", data });
    },
  };
};
const mapStateToProps = (state) => {
  return {
    user: state.user,
    code: "",
    url: ''
  };
};

class Login extends Component {
  componentDidMount() {
    localStorage.clear()
    if (this.props.user) {
      this.props.history.push("/home");
      return
    }
    this.imgChange()
    document.getElementById('viewport').setAttribute('content', 'width=device-width, minimum-scale=1.0, initial-scale=1, maximum-scale=1.0, user-scalable=no');
  }

  state = {
    loading: false,
    key: new Date().getTime(),
  };
  /**
   * @desc 登录事件
   * @params object {values} 登录表单提交事件
   * */
  handleSubmit = async (values) => {
    this.setState({ loading: true });
    values = { ...values, areaCode: 'admin' }

    React.$post('/management/auth/store/login', values).then(data => {
      if (data.code === 0) {
        sessionStorage.setItem('businessCategory', data.data.businessCategory);
        sessionStorage.setItem('RSnetToken', data.data.token);
        sessionStorage.setItem('roleName', data.data.roleName);
        this.props.updateUser(data.data);
        React.$post('/management/sysStoreIdent/getMenuIdentListByUserId').then(res => {
          const ident = res.data.idents.map(v => v.identType)
          this.props.updateIdent(ident)
          sessionStorage.setItem('menuList', JSON.stringify(res.data.menus))
          window.location.reload();
          React.$message({
            type: "success",
            content: '登录成功!'  
            
          });
        })
      } else {
        this.imgChange()
      }
      this.setState({ loading: false })
    }).catch(e => {
      this.setState({ loading: false })
    })
  };

  componentWillUnmount() {
    notification.destroy();
    this.timer && clearTimeout(this.timer);
  }

  /**
   * @desc 切换验证图片
   * */
  imgChange = async () => {
    let res = await getCaptcha(new Date().getTime())
    var binary = "";
    var bytes = new Uint8Array(res);
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    var base64 = `data:image/png;base64,${window.btoa(binary)}`
    console.log(base64)
    this.setState({
      url: base64,
      key: new Date().getTime(),
    });
  };
  /**
   * @desc 验证码效验规则
   * */
  onChange = (e) => {
    let val = e.target.value.trim();
    if (val.length > 4) {
      val = val.slice(0, 4);
    }
    this.loginForm.setFieldsValue({ captcha: val });
  };

  render() {
    const { loading, key, code, url } = this.state;
    return (
      <Layout className="login animated fadeIn" style={{ backgroundSize: `${window.innerWidth}px ${window.innerHeight}px` }}>
        {/* <ParticlesBg
          type="cobweb"
          bg={true}
          className={"canvas-back"}
          style={{ zIndex: 1 }}
          color="#EEEEEE"
        /> */}
        <div className="model">
          <div className="login-form">
            <div className="login-logo"></div>
            <h3>登录 门店管理平台</h3>
            <Divider style={{ margin: "30px auto" }} />
            <Form
              ref={(ref) => {
                this.loginForm = ref;
              }}
              onFinish={this.handleSubmit}
              style={{ width: 276, margin: '0 auto' }}
            >
              <Form.Item
                className={"form-item"}
                name="loginName"
              // rules={[
              //   { required: true, message: "输入手机号!" },
              //   {
              //     whitespace: true,
              //     message: "不能包含空格字符",
              //   },
              // ]}
              >
                <React.FormInput placeholder="请输入账号" />
              </Form.Item>
              <Form.Item
                className={"form-item"}
                name="password"
              // rules={[{ required: true, message: "请输入密码!" }]}
              >
                <React.FormPassword placeholder="请输入密码" />
              </Form.Item>
              <Form.Item
                className={"captcha-item"}
                name="captcha"
              // rules={[
              //   {
              //     required: true,
              //     message: "请输入验证码!",
              //   },
              //   { validator: this.validator },
              //   { min: 4, message: "验证码为4个字符" },
              //   {
              //     whitespace: true,
              //     message: "不能包含空格字符",
              //   },
              // ]}
              >
                <div>
                  <React.FormInput
                    style={{ width: 130 }}
                    onChange={this.onChange}
                    placeholder="请输入验证码"
                  />
                  <div
                  // className="clearfix code-change-box"
                  >
                    <TheImage
                      placeholder={
                        !url ? <div className="img-center-label">
                          <LoadingOutlined />
                        </div> : false
                      }
                      className={"fl"}
                      src={url}
                      // src={"/pro-management/management/" + "auth/captcha?" + key}
                      key={key}
                      width={"126px"}
                      height={"50px"}
                      preview={false}
                      onClick={this.imgChange}
                    />
                    {/* <span className="code-change-btn fr" onClick={this.imgChange}>
                      换一张
                    </span> */}
                  </div>
                </div>
              </Form.Item>

              <Form.Item className={"form-item"}>
                <Button
                  type="primary"
                  htmlType="submit"
                  className="login-form-button"
                  loading={loading}
                >
                  登录
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </Layout >
    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);
